package cn.wolfcode.wolf2w.interceptor;

import cn.wolfcode.wolf2w.annotation.RequireLogin;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆拦截器
 */
public class CheckLoginInterceptor implements HandlerInterceptor{

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{

        //  若是就拦下来
        //  .addPathPatterns("/**") 拦下所有映射路径
        //  不是才被放行
        //  .excludePathPatterns("/users/regist")   放行该映射路径
        if (!(handler instanceof HandlerMethod)) {
            //  代码继续向下执行
            return true;
        }

        HandlerMethod hm = (HandlerMethod) handler;

        String token = request.getHeader("token");
        UserInfo user = userInfoRedisService.getToken(token);


/*        if (user == null) {
            response.setContentType("application/json; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
            return false;
        }*/

        //  判断是否有贴自定义注解
        if (hm.hasMethodAnnotation(RequireLogin.class)) {
            //  若对象为空
            if (user == null) {
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().write(JSON.toJSONString(JsonResult.noLogin()));
                //  直接结束方法
                return false;
            }
        }
        //  没贴注解直接放行
        return true;
    }
}
